<?

ini_set('error_reporting', E_ALL);
ini_set('display_errors', 'On');


$query = <<<QUERY

SELECT
	s.inst_name as name,
	s.address1 as address,
	s.city,
	s.zipcode as zip,
	s.enrollment,
	AsKML(s.the_geom) as kml
FROM
        schools as s
ORDER BY
	s.inst_name
QUERY;

// print $query;
//header('Content-type: application/vnd.google-earth.kml+xml');

$conn = pg_connect("dbname=rvha user=pgadmin password=pgadmin");
	if (!$conn)
	{
       	 	print "Unable to Connect to DB";
	        exit;
	}


$result = pg_query($query);

print <<<KML_TOP
<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="http://earth.google.com/kml/2.2">
<Document>
	<name>Salt Lake County - Schools</name>
	<description>
	This data is based on information from the Utah Automated Geographic Reference Center (AGRC). 
	Information regarding the school data can be found at:
	1) ftp://ftp.agrc.state.ut.us/SGID_Vector/MetadataHTML/SGID_U024_Schools.html
	2) ftp://ftp.agrc.state.ut.us/SGID_Vector/MetadataHTML/SGID_U100_UniversitiesGNIS.html
	</description>
	<Style id="trb818" x="12" y="12" xunits="pixels" yunits="pixels">
		<IconStyle>
			<Icon>
				<href>http://maps.google.com/mapfiles/kml/shapes/﻿ranger_station.png</href>
			</Icon>
			<hotSpot x="0" y="0" xunits="pixels" yunits="pixels"/>
		</IconStyle>
	</Style>
KML_TOP;

$counter = 0;
while( $arr = pg_fetch_array($result))
{
	$kml = $arr["kml"];
	$name = $arr['name'];
	$address = $arr['address'];
	$city = $arr['city'];
	$zip = $arr['zip'];
	$enrollment = $arr['enrollment'];

	if($enrollment == "0")
	{
		$enrollment = "Unknown";
	}
	$desc = "<![CDATA[";
	$desc .= " $address $city $zip<br/>";
	$desc .= " Enrollment: $enrollment<br/>";
	$desc .= "]]>";

	print "\n<Placemark id=\"$counter\">";
	print "\n<name>".htmlentities($name)."</name>";
	print "\n<description>".$desc."</description>";
	print "<styleUrl>#trb818</styleUrl>";
	print "$kml";
	print "</Placemark>";
	$counter++;
}

print <<<KML_BOTTOM
</Document>
</kml>

KML_BOTTOM;

?>
